﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using MyBet.Helpers;
using System.Globalization;
using MyBet.Controls;
using System.Collections.Generic;
using ChartReversedAxis;
using System.Windows.Controls.DataVisualization.Charting;

namespace MyBet
{
	public partial class MyAccountControl : UserControl
	{

        public delegate void CustomContestChangeDelegate();
        public event CustomContestChangeDelegate OnCustomContestChanged;

        private bool _isFirstLoad = true;
        private bool _isListLoaded = false;

		public MyAccountControl()
		{
			// Required to initialize variables
			InitializeComponent();
		}

        #region Globalization
        /// <summary>
        /// Update labels after changing culture
        /// </summary>
        public void UpdateCulture()
        {
            RankLabel.Text = LangHelper.GetString("Rank");
            ScoreLabel.Text = LangHelper.GetString("Score");
            ScoreAverageLabel.Text = LangHelper.GetString("AverageScore");
            RegistrationDateLabel.Text = LangHelper.GetString("RegistrationDate");
            EventPlayedLabel.Text = LangHelper.GetString("EventsPlayed");
            BestScoreLabel.Text = LangHelper.GetString("EventWonLabel");

            //DisjoinButton.Content = LangHelper.GetString("Disjoin");

            //ChangeAccountButton.Content = LangHelper.GetString("ChangeAccountButton");


            ScoreMaxLabel.Text = LangHelper.GetString("ScoreMax");
            ScoreMinLabel.Text = LangHelper.GetString("ScoreMin");
            MyAccountTitle.Text = LangHelper.GetString("TabMyAccountHeader");
            EmailLabel.Text = LangHelper.GetString("Email");

            if (App.CurrentUser != null)
            {
                MyAccountGroupBox.Header = String.Format("{0} - {1}", LangHelper.GetString("YourAccount"), App.CurrentUser.UserName);
                if (App.CurrentUser.CreationDate.HasValue)
                {
                    RegistrationDateTxt.Text = App.CurrentUser.CreationDate.Value.ToString(new CultureInfo(LangHelper.GetString("CultureInfo")));
                }
                else
                {
                    RegistrationDateTxt.Text = "-";
                }
            }
            else
            {
                MyAccountGroupBox.Header = "";
            }



        }
        #endregion

        #region Modify account functions

        private void ChangeAccountButton_Click(object sender, System.Windows.RoutedEventArgs e)
		{
            ModifyAccountDialog dialog = new ModifyAccountDialog();
            dialog.Show();
        }



        #endregion

        #region Join/disjoin functions
        //private void DisjoinButton_Click(object sender, System.Windows.RoutedEventArgs e)
        //{
        //    Error dlgConfirm = new Error(LangHelper.GetString("ConfirmDisjoinTitle"), LangHelper.GetString("ConfirmDisjoin"), Error.ErrorType.Question);
        //    dlgConfirm.Closed += new EventHandler(dlgConfirm_Closed);
        //    dlgConfirm.Show();
        //}

        //// Confirm / Cancel disjoin
        //void dlgConfirm_Closed(object sender, EventArgs e)
        //{
        //    Error cw = (Error)sender;
        //    if (cw.DialogResult == true)
        //    {
        //        BusyControl.IsBusy = true;
        //        JoinServiceReference.JoinServiceClient joinSvc = new JoinServiceReference.JoinServiceClient();
        //        joinSvc.DisjoinContestCompleted += new EventHandler<JoinServiceReference.DisjoinContestCompletedEventArgs>(joinSvc_DisjoinContestCompleted);
        //        joinSvc.DisjoinContestAsync(App.CurrentUser.UserId, App.CurrentUser.CurrentContestId);
        //    }
        //}

        ///// <summary>
        ///// Call to disjoin service is completed
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //void joinSvc_DisjoinContestCompleted(object sender, JoinServiceReference.DisjoinContestCompletedEventArgs e)
        //{
        //    String message;
        //    Error dlg;

        //    switch (e.Result)
        //    {
        //        case MyBet.JoinServiceReference.CustomContestObject.DisjoinContestStatus.Success:
        //            message = LangHelper.GetString("DisjoinSuccessMessage");
        //            dlg = new Error("", message, Error.ErrorType.Info);
        //            dlg.Show();
        //            OnDisjoinContest();
        //            break;
        //        case MyBet.JoinServiceReference.CustomContestObject.DisjoinContestStatus.NotSubscribe:
        //            message = LangHelper.GetString("DisjoinFailedMessageNotSubscribe");
        //            dlg = new Error("", message, Error.ErrorType.CriticalError);
        //            dlg.Show();
        //            break;
        //        case MyBet.JoinServiceReference.CustomContestObject.DisjoinContestStatus.GeneralFailure:
        //            message = LangHelper.GetString("DisjoinFailedMessage");
        //            dlg = new Error("", message, Error.ErrorType.CriticalError);
        //            dlg.Show();
        //            break;
        //        default:
        //            break;
        //    }

                
                
                
        //    //}
        //    //else
        //    //{
        //    //    
        //    //}
        //    BusyControl.IsBusy = false;
        //}

        #endregion

        private void GenerateRankEvolutionRank(SecurityServiceReference.UserObject user)
        {
            List<KeyValuePair<int, int>> ranks = new List<KeyValuePair<int, int>>();
            int i=1;

            foreach (int rank in user.RankEvolution)
            {
                ranks.Add(new KeyValuePair<int,int>(i, rank));
                i++;
            }

            if (ranks.Count > 0)
            {
                // Définition de l'axe des abscisses
                RankChart.DataContext = ranks;
                LinearAxis newAxisX = new LinearAxis();
                newAxisX.Orientation = AxisOrientation.X;
                newAxisX.Minimum = 1;
                newAxisX.Maximum = i;
                newAxisX.Location = AxisLocation.Bottom;
                newAxisX.FontSize = 8;

                // Définition de l'axe des ordonnées (inversé pour que le premier au classement soit en haut)
                ReversedLinearAxis newAxisY = new ReversedLinearAxis();
                newAxisY.Orientation = AxisOrientation.Y;
                newAxisY.Minimum = 0.5;
                newAxisY.Maximum = user.CustomContestPlayerCount;
                newAxisY.Location = AxisLocation.Left;
                newAxisY.FontSize = 8;
                newAxisY.ShowGridLines = true;

                ((ReversedAxisLineSeries)RankChart.Series[0]).IndependentAxis = newAxisX;
                ((ReversedAxisLineSeries)RankChart.Series[0]).DependentRangeAxis = newAxisY;
                ChartStackPanel.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                RankChart.DataContext = null;
                ((ReversedAxisLineSeries)RankChart.Series[0]).IndependentAxis = null;
                ((ReversedAxisLineSeries)RankChart.Series[0]).DependentRangeAxis = null;
                //ChartStackPanel.Visibility = System.Windows.Visibility.Collapsed;
            }

        }


        /// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            LoadUser();
            if ((App.CurrentUser != null) && (!_isListLoaded))
            {
                JoinServiceReference.JoinServiceClient joinSvc2 = new JoinServiceReference.JoinServiceClient();
                joinSvc2.GetSubscriptionCompleted += new EventHandler<JoinServiceReference.GetSubscriptionCompletedEventArgs>(joinSvc2_GetSubscriptionCompleted);
                joinSvc2.GetSubscriptionAsync(App.CurrentUser.UserId);
            }
        }

        private void LoadUser()
        {
            if (App.CurrentUser != null)
            {
                if (App.CurrentUser.AverageScore.HasValue)
                {
                    ScoreAverageTxt.Text = App.CurrentUser.AverageScore.ToString();
                }
                else
                {
                    ScoreAverageTxt.Text = "-";
                }
                if (App.CurrentUser.MinScore.HasValue)
                {
                    ScoreMinTxt.Text = App.CurrentUser.MinScore.ToString();
                }
                else
                {
                    ScoreMinTxt.Text = "-";
                }
                if (App.CurrentUser.MaxScore.HasValue)
                {
                    ScoreMaxTxt.Text = App.CurrentUser.MaxScore.ToString();
                }
                else
                {
                    ScoreMaxTxt.Text = "-";
                }
                EventPlayedTxt.Text = String.Empty;
                if (App.CurrentUser.BetCount.HasValue)
                {
                    EventPlayedTxt.Text = App.CurrentUser.BetCount.ToString();
                }
                else
                {
                    EventPlayedTxt.Text = "-";
                }
                if (App.CurrentUser.MaximumBetCount.HasValue)
                {
                    EventPlayedTxt.Text += " / " + App.CurrentUser.MaximumBetCount.ToString();
                }
                else
                {
                    EventPlayedTxt.Text += " / -";
                }

                if (App.CurrentUser.TotalScore.HasValue)
                {
                    ScoreTxt.Text = App.CurrentUser.TotalScore.ToString();
                }
                else
                {
                    ScoreTxt.Text = "-";
                }

                if (App.CurrentUser.BestOfEventCount.HasValue)
                {
                    BestScoreTxt.Text = App.CurrentUser.BestOfEventCount.Value.ToString();
                }
                else
                {
                    BestScoreTxt.Text = "-";
                }

                if (!App.CurrentUser.Rank.HasValue)
                {
                    RankTxt.Text = "-";
                }
                else if (App.CurrentUser.Rank > 0)
                {
                    RankTxt.Text = App.CurrentUser.Rank.ToString();
                }
                else
                {
                    RankTxt.Text = "-";
                }

                // Génération du graphique de l'évolution des scores
                GenerateRankEvolutionRank(App.CurrentUser);

                EmailTxt.Text = App.CurrentUser.Email;
            }
        }

        void joinSvc2_GetSubscriptionCompleted(object sender, JoinServiceReference.GetSubscriptionCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                ExceptionErrorDialog dlg = new ExceptionErrorDialog("Erreur interne", e.Error.GetType().FullName + "\n" + e.Error.Message, ExceptionErrorDialog.ErrorType.CriticalError);
                dlg.Show();
                return;
            }
            else if (e.myFault != null)
            {
                ExceptionErrorDialog dlg = new ExceptionErrorDialog("Erreur interne", e.myFault.FaultType + "\n" + e.myFault.Message, ExceptionErrorDialog.ErrorType.CriticalError);
                dlg.Show();
                return;
            }
            else if (e.Result != null)
            {
                CustomContestList.Items.Clear();
                foreach (JoinServiceReference.CustomContestObject item in e.Result)
                {
                    JoinContest.Contest newContest;
                    newContest = new JoinContest.Contest { id = item._id, displayName = String.Format("{0}", item._displayName.Trim()) };
                    newContest.displayName = String.Format("{0}", newContest.displayName);
                    CustomContestList.Items.Add(newContest);
                    if ((item._isDefaultContest.HasValue) && (item._isDefaultContest.Value == 1))
                    {
                        CustomContestList.SelectedItem = newContest;
                    }
                }
                _isListLoaded = true;
            }
        }

        private void CustomContestList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (!_isFirstLoad)
            {
                JoinContest.Contest currentSelection = CustomContestList.SelectedItem as JoinContest.Contest;
                if (currentSelection != null)
                {
                    BusyControl.IsBusy = true;
                    SecurityServiceReference.SecurityServiceClient securitySvc = new SecurityServiceReference.SecurityServiceClient();
                    securitySvc.LoadUserFromCustomContestCompleted += new EventHandler<SecurityServiceReference.LoadUserFromCustomContestCompletedEventArgs>(securitySvc_LoadUserFromCustomContestCompleted);
                    securitySvc.LoadUserFromCustomContestAsync(App.CurrentUser.UserName, currentSelection.id);
                }
            }
            else
            {
                _isFirstLoad = false;
            }
        }

        void securitySvc_LoadUserFromCustomContestCompleted(object sender, SecurityServiceReference.LoadUserFromCustomContestCompletedEventArgs e)
        {
            BusyControl.IsBusy = false;
            if (e.Result != null)
            {
                App.CurrentUser = e.Result;
                LoadUser();
                OnCustomContestChanged();
            }
            else
            {
                MessageBox.Show("Impossible de charger les résultats de ce tournoi");
            }

        }

        //private void ReinitButton_Click(object sender, RoutedEventArgs e)
        //{
        //    SecurityServiceReference.SecurityServiceClient securitySvc = new SecurityServiceReference.SecurityServiceClient();
        //    securitySvc.ReinitUserPasswordCompleted += new EventHandler<SecurityServiceReference.ReinitUserPasswordCompletedEventArgs>(securitySvc_ReinitUserPasswordCompleted);
        //    securitySvc.ReinitUserPasswordAsync("Gouv", "$KsioP35");
        //}

        //void securitySvc_ReinitUserPasswordCompleted(object sender, SecurityServiceReference.ReinitUserPasswordCompletedEventArgs e)
        //{
        //    if (e.Result)
        //    {
        //        MessageBox.Show("Password reinit");
        //    }
        //    else
        //    {
        //        MessageBox.Show("Password reinit failed !!");
        //    }
        //}
	}
}